package leetCode.offer42;

public class Solution5 implements Solution{

    /**
     * 相比解法4更加优秀的解法
     * @param nums
     * @return
     */
    @Override
    public int maxSubArray(int[] nums) {
        // 特殊情况处理
        if(nums.length==1) return nums[0];
        // 存储子数组之和
        int sum = 0;
        int min = 0;
        int result = -Integer.MAX_VALUE;
        int temResult = -Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++) {
            sum += nums[i];
            if(min>sum){
                min  = sum;
            }else if(result<sum-min){
                result = sum - min;
            }
            if(temResult<nums[i]){
                temResult = nums[i];
            }
        }
        if(result==-Integer.MAX_VALUE){
            result = temResult;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] param = {1,2};
        System.out.println(new Solution5().maxSubArray(param));
    }

}
